<template>
  <div class="create-wrap">
    <ChartTop v-if="!isEdit" :active="active" @tabTab="tabTab" />
    <div :class="{'create-class': !isEdit}" class="chart-create-container">
      <div class="chart-create-main">
        <CreateOverviewModule v-if="active === 0" ref="createOverviewModule" :process="process" :edit-type="editType" :is-edit="isEdit" :tab-id="tabId" @switchProcess="itemClick" @goBack="goBack" />
        <CreateChartModule v-if="active === 1" ref="createChartModule" :process="process" :edit-type="editType" :is-edit="isEdit" :tab-id="tabId" @switchProcess="itemClick" @goBack="goBack" />
        <CreateTableModule v-if="active === 2" ref="createTableModule" :process="process" :edit-type="editType" :is-edit="isEdit" :tab-id="tabId" @switchProcess="itemClick" @goBack="goBack" />
        <CreateTitleModule v-if="active === 4" ref="createTitleModule" :edit-type="editType" :is-edit="isEdit" :tab-id="tabId" @goBack="goBack" />
        <CreateHomeModule v-if="active === 5" ref="createHomeModule" :edit-type="editType" :is-edit="isEdit" :tab-id="tabId" @goBack="goBack" />
      </div>
      <!-- 导航 -->
      <div v-if="navList && navList.length" :style="{width: isNavOpen ? '140px' : '0px'}" class="nav-wrap">
        <div :style="{padding: isNavOpen ? '12px 0' : '0'}" class="nav-list">
          <div v-for="item in navList" v-show="isNavOpen" :key="item.id" :class="currentNav === item.id && 'active'" class="item" @click="changeNav(item, true)">
            <Ellipsis :content="item.name" placement="left" />
          </div>
          <div v-if="isNavOpen" class="close-btn btn" @click="switchShow">
            <img :src="closeIcon">
          </div>
          <div v-else class="open-btn btn" @click="switchShow">
            <img :src="openIcon">
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
// api
import { chartDetail } from '@/api/reportManage';
// components
import Step from '@/components/CreateOrder/orderDetail/step';
import ChartTop from '@/components/ReportManage/chartCreate/topBar';
// module
import CreateOverviewModule from './module/createOverviewModule/index';
import CreateChartModule from './module/createChartModule/index';
import CreateTableModule from './module/createTableModule/index';
import CreateHomeModule from './module/createHomeModule';
// 新建标题模块
import CreateTitleModule from '@/components/ReportManage/chartCreate/createTitleModule';
import { showModal } from '@/utils/message';
import openIcon from '@/assets/medium/openIcon.png';
import closeIcon from '@/assets/medium/closeIcon.png';

export default {
  components: {
    Step,
    ChartTop,
    CreateOverviewModule,
    CreateChartModule,
    CreateTableModule,
    CreateHomeModule,
    CreateTitleModule
  },
  data() {
    return {
      openIcon,
      closeIcon,
      isNavOpen: true,
      isClickScrolling: false,
      currentNav: 'data',
      process: 0,
      active: 0,
      chartId: '',
      isEdit: false,
      detailData: null,
      tabId: '',
      editType: 'edit' // edit or copy
    };
  },
  computed: {
    navList() {
      if ([0, 1, 2].includes(this.active)) { return [{ id: 'data', name: '数据配置' }, { id: 'style', name: '样式配置' }]; }
      return [];
    }
  },
  created() {
    this.chartId = this.$route.params.id || '';
    this.tabId = this.$route.query.tabId || '';
    this.editType = this.$route.query.type || 'edit';
    if (this.chartId && this.chartId !== '') {
      this.isEdit = true;
      this.getDetailData();
    } else {
      this.isEdit = false;
    }
    this.$store.dispatch('GetColorList');
  },
  mounted() {
    setTimeout(() => {
      window.addEventListener('scroll', this.handleCurrentNav);
    }, 1000);
  },
  destroyed() {
    window.removeEventListener('scroll', this.handleCurrentNav);
  },
  methods: {
    itemClick(item) {
      this.process = item.id;
    },
    getDetailData() {
      chartDetail({ id: this.chartId }).then(res => {
        if (res.code === 200) {
          if (res.data.chartFilter && res.data.chartFilter.length) {
            res.data.chartFilter.forEach(item => {
              item._id = new Date().valueOf() + '_' + Math.ceil(Math.random() * 99999);
            });
          }
          if (res.data.tags && res.data.tags.length) {
            res.data.tags.forEach(item => {
              item.showEditTagFormula = false;
              item.tagFormula && (item.tagFormulaText = item.tagFormula.replace(/#/g, ''));
            });
          }
          if (res.data.selectField && res.data.selectField.length) {
            res.data.selectField.forEach(item => {
              item.showEditTagFormula = false;
              item.tagFormula && (item.tagFormulaText = item.tagFormula.replace(/#/g, ''));
            });
          }
          this.detailData = res.data;
          const kind = res.data.kind;
          this.insertData(kind, res.data);
        }
      });
    },
    // 插入编辑数据
    insertData(kind, data) {
      // kind 1:概览标签，2:表格，3:图表
      switch (kind) {
        case 1:
          this.active = 0;
          this.title = '概览标签模块';
          this.$nextTick(() => {
            this.$refs.createOverviewModule.setDefault(data);
          });
          break;
        case 2:
          this.active = 2;
          this.title = '表格模块';
          this.$nextTick(() => {
            this.$refs.createTableModule.setDefault(data);
          });
          break;
        case 3:
          this.active = 1;
          this.title = '图表模块';
          this.$nextTick(() => {
            this.$refs.createChartModule.setDefault(data);
          });
          break;
        case 4:
          this.active = 3;
          this.title = '数字翻页器';
          this.$nextTick(() => {
            this.$refs.createNumberModule.setDefault(data);
          });
          break;
        case 5:
          this.active = 4;
          this.title = '标题图';
          this.$nextTick(() => {
            this.$refs.createTitleModule.setDefault(data);
          });
          break;
        case 6:
          this.active = 5;
          this.$nextTick(() => {
            this.$refs['createHomeModule'].setDefault(data);
          });
          break;
      }
    },
    tabChange(item) {
      this.active = item;
      this.process = 0;
      let kind = 1;
      switch (item) {
        case 0:
          this.title = '概览标签模块';
          kind = 1;
          break;
        case 1:
          this.title = '图表模块';
          kind = 3;
          break;
        case 2:
          this.title = '表格模块';
          kind = 2;
          break;
        case 3:
          this.title = '数字翻页器模块';
          kind = 4;
          break;
        case 4:
          this.title = '标题图模块';
          kind = 5;
          break;
        case 5:
          kind = 6;
          break;
      }
      if (this.detailData) this.insertData(kind, this.detailData);
    },
    tabTab(item) {
      if (this.isDataChange() && this.active !== item) {
        showModal('当前页面有数据，是否切换图表模块，切换后原有数据将不保留', '', {
          iconClass: 'del-icon'
        }).then(() => {
          this.tabChange(item);
        });
      } else {
        this.tabChange(item);
      }
    },
    isDataChange() {
      const refName = {
        0: 'createOverviewModule',
        1: 'createChartModule',
        2: 'createTableModule',
        4: 'createTitleModule',
        5: 'createHomeModule'
      }[this.active];
      return this.$refs[refName].isDataChange();
    },
    goBack() {
      const params = {
        tabId: this.tabId,
        from: 'chartCreat'
      };
      if (this.$route.query.editMobileMode) params.editMobileMode = this.$route.query.editMobileMode;
      const isFirstPage = this.$route.query.isFirstPage;
      if (isFirstPage) {
        params.edit = 1;
      }
      this.$router.push({
        name: 'dashboard',
        query: params
      });
    },
    handleCurrentNav: _.debounce(function() {
    // 手动点击Nav不触发监听
      if (!this.isClickScrolling) {
        this.navList.forEach(it => {
          const ele = document.querySelector(`#${it.id}`);
          if (ele) {
            const eleTop = ele.getBoundingClientRect().top;
            it.top = eleTop;
          }
        });
        // 取top绝对值的最小值
        const currentNav = this.navList.find(i => Math.abs(i.top) === Math.min(...this.navList.filter(k => k.top).map(j => Math.abs(j.top))));
        this.changeNav(currentNav);
      }
    }, 500),
    changeNav({ id }, isClick = false) {
      if (id) {
        if (isClick) {
          this.isClickScrolling = true;
          const dom = document.getElementById(id);
          dom && dom.scrollIntoView({ behavior: 'smooth' });
          setTimeout(() => {
            this.isClickScrolling = false;
          }, 1500);
        }
        this.currentNav = id;
      }
    },
    switchShow() {
      this.isNavOpen = !this.isNavOpen;
    }
  }
};
</script>

<style lang="scss" scoped>
.create-wrap {
  margin: 16px;
  display: flex;
}
.chart-create-container {
  flex: 1;
  background-color: #fff;
  min-height: calc(100vh - 80px);
  padding-bottom: 70px;
  border-left: 1px #ddd solid;
}
.create-class {
  border: none;
  box-shadow: -2px 5px 10px -5px rgb(122 131 149 / 63%);
}
.chart-create-main {
  margin: 0 24px;
  &::v-deep {
    .el-checkbox {
      .el-checkbox__label {
        padding-left: 4px;
      }
    }
  }
}
.nav-wrap {
  width: 140px;
  transition: width .25s ease;
  flex-shrink: 0;
  .btn {
    position: absolute;
    display: flex;
    justify-content: center;
    align-items: center;
    background: #406EFF;
    border-radius: 4px 0 0 4px;
    cursor: pointer;
    img {
      width: 6px;
      height: 5px;
    }
  }
  .open-btn {
    top: 24px;
    left: -10px;
    width: 10px;
    height: 40px;
    color: #fff;
  }
  .close-btn {
    top: 24px;
    left: -10px;
    width: 10px;
    height: 40px;
  }
  .nav-list {
    position: fixed;
    top: 80px;
    right: 16px;
    z-index: 21;
    background-color: #fff;
    border-radius: 8px 0px 0px 8px;
    box-shadow: 0px 0px 6px 0px #dddddd;
    .item {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 116px;
      height: 28px;
      padding: 0 12px;
      margin: 0 12px;
      font-family: PingFangSC-Regular;
      color: #666666;
    }
    .item:hover, .item.active {
      background: #EDEEF2;
      border-radius: 2px;
      cursor: pointer;
    }
    .item.active {
      font-weight: bold;
      color: #406EFF;
    }
  }
}
</style>
